#include "flash.h"
#include "string.h"
static uint8_t buff[PAGE_SIZE];

uint8_t FlashCheckSectorErase(uint32_t addr, uint8_t *data)
{
    uint16_t i;
    FlashRead(addr, data, SECTOR_SIZE);
    for(i=0;i<SECTOR_SIZE;i++)
    {
        if(data[i] != 0xFF)
            return 1;
    }
    return 0;
}


uint32_t  FlashGetPageAddr(uint32_t addr)
{
    return (addr - (addr % PAGE_SIZE));
}

uint8_t FlashWritePage(uint32_t pageAddress, uint32_t *data)
{
    FLASH_ProgramPage_Fast(pageAddress, data);
    return 1;
}


void FlashWrite(uint32_t addr, uint8_t *data, uint16_t len)
{
        if((addr >= DATA_ADDRESS_START) && ((addr + len) < DATA_ADDRESS_END))
        {
            uint32_t pageAssress;
            uint16_t writed = 0;
            uint16_t toWrite;
            uint16_t offset;
            FLASH_Unlock_Fast();
            while(writed < len)
            {
                pageAssress = FlashGetPageAddr(addr);
                FlashRead(pageAssress, (uint8_t*)buff, PAGE_SIZE);
                FLASH_ErasePage_Fast(pageAssress);
                offset = addr - pageAssress;
                toWrite = ((len - writed) < (PAGE_SIZE - offset) ? (len - writed) : (PAGE_SIZE - offset));
                memcpy(buff + offset, data + writed, toWrite);
                if(FlashWritePage(pageAssress, (uint32_t*)buff)==0)
                    break;

                writed += toWrite;
                addr += toWrite;
            }
            FLASH_Lock_Fast();
        }
}


void FlashRead(uint32_t addr, uint8_t *data, uint16_t len)
{
    uint16_t i;
    if((addr >= DATA_ADDRESS_START) && ((addr + len) < DATA_ADDRESS_END))
    {
        for(i=0;i<len;i++)
        {
            data[i] = *(uint8_t*)(addr+i);
        }
    }
} 

